package com.yuyu.qingmang.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("userInfo")
    public String userInfo(@RequestParam("token") String token) {

        String s = redisTemplate.opsForValue().get(token);
        return s;
    }

    @GetMapping("login.html")
    public String login(@RequestParam("redirect_url") String redirectUrl, Model model,
                        @CookieValue(value = "ssotoken",required = false) String ssotoken) {

        if (ssotoken!=null){
            // 登陆过了
            return "redirect:"+redirectUrl+"?token="+ssotoken;
        }
        model.addAttribute("redirect_url",redirectUrl);
        return "login";
    }

    @PostMapping("/dologin.html")
    public String doLogin(@RequestParam("userName") String userName,
                          @RequestParam("password") String password,
                          @RequestParam("redirect_url") String redirectUrl,
                          HttpServletResponse response){

            if (userName!=null && password!=null){
                //登录成功

                // 把登录成功的用户存起来
                String uuid = UUID.randomUUID().toString().replace("_","");
                redisTemplate.opsForValue().set(uuid,userName);
                Cookie token = new Cookie("ssotoken", uuid);
                response.addCookie(token);

                return "redirect:"+redirectUrl+"?token="+uuid;
            }else {
                // 登陆失败
                return "login";
            }



    }
}
